package cn.jasonone.at.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import cn.jasonone.at.template.syntax.Syntax;
/**
 * Sql解析工具类
 * @author Jason
 *
 */
@Component
public class SqlUtil implements ApplicationContextAware {

	private static final List<Syntax> SYNTAXS=new ArrayList<>(5);
	private static final Pattern PATTERN = Pattern.compile("@\\{[^\\}]+\\}");

	/**
	 * 解析SQL
	 * 
	 * @param sql sql
	 * @param context 上下文环境
	 * @return sql
	 */
	public static String parseSql(String sql, Map<String, Object> context) {
		
		Matcher matcher = PATTERN.matcher(sql);
		while (matcher.find()) {
			String s = matcher.group();
			String value = "";
			// 处理自定义语法
			for (Syntax syntax : SYNTAXS) {
				if(syntax.isSyntax(s)) {
					value = syntax.parse(s, context);
				}
			}
			if(StringUtils.isBlank(value)) {
				value = s.substring(2, s.length() - 1);
				if (context.containsKey(value)) {
					value = Objects.toString(context.get(value));
				} else {
					value = "";
				}
			}
			sql = sql.replace(s, value);
		}
		return sql;
	}
	/**
	 * 初始化工具类
	 * @param syntaxs 语法解析器
	 */
	public static void init(Collection<Syntax> syntaxs) {
		SYNTAXS.addAll(syntaxs);
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		Map<String, Syntax> beansOfType = applicationContext.getBeansOfType(Syntax.class);
		SYNTAXS.addAll(beansOfType.values());
	}
}
